package com.softmaker.service;

import com.softmaker.entity.UserInfo;
import com.softmaker.entity.UserPoint;
import com.softmaker.repository.UserInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserInfoService {
    @Autowired
    private UserInfoRepository repository;
    public UserInfo addStudent(UserInfo userInfo)  {
        userInfo.setUserId(UUID.randomUUID().toString());
        LocalDate localDate = LocalDate.now().minusDays(1);
        ZoneId zoneId = ZoneId.systemDefault();
        Date date = Date.from(localDate.atStartOfDay().atZone(zoneId).toInstant());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String datef = sdf.format(date);
        userInfo.setDate(datef);
        return repository.save(userInfo);
    }
    public UserInfo findUser(UserInfo userInfo){
        return repository.findUserInfoByUserName(userInfo.getUserName());
    }
    @Transactional
    public void deleteUserInfoByUserName(String userName){
        repository.deleteUserInfoByUserName(userName);
    }
    @Transactional
    public UserInfo updatePasswordByUserName(UserInfo userInfo){
        repository.updatePasswordByUserName(userInfo.getPassword(), userInfo.getUserName());
       return repository.findByUserName(userInfo.getUserName());
    }
    public Page listUser(Pageable pageable){
        return repository.findAll(pageable);
    }
    public void addUserCount(UserPoint userPoint){
        UserInfo userInfo = repository.findByUserName(userPoint.getUserName());
        int count = userInfo.getCount();
        count += userPoint.getPoints();
        userInfo.setCount(count);
        repository.save(userInfo);
    }
    public int getUserCount(String userName){
        UserInfo userInfo = repository.findByUserName(userName);
        return userInfo.getCount();
    }
    public String getCheckTime(String userName){
        UserInfo userInfo = repository.findByUserName(userName);
        return userInfo.getCheckTime();
    }
    public void addCheckTime(String userName,String datef){
        UserInfo userInfo = repository.findByUserName(userName);
        userInfo.setCheckTime(datef);
        repository.save(userInfo);
    }
    public List<String> getVideoNameByUserId(String userId){
        return repository.getVideoNameByUserId(userId);
    }

}
